package com.finger.wx.assistant.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

public class ToolHttp {
	private static final int CONNECT_TIMEOUT = 10000;
	private static final int READ_TIMEOUT = 10000;

	/**
	 * 发送HTTP GET请求
	 * */
	public static String doGet(String url, String param, Map<String, String> headers, String charset) {
		StringBuffer response = new StringBuffer();
		BufferedReader in = null;
		try {
			String _url = url;
			if (param != null) {
				_url += url.contains("?") ? "&" + param : "?" + param;
			}
			// 打开和URL之间的连接
			URLConnection conn = (new URL(_url)).openConnection();
			conn.setReadTimeout(READ_TIMEOUT);
			conn.setConnectTimeout(CONNECT_TIMEOUT);
			// 设置通用的请求属性
			if (headers != null) {
				for (Map.Entry<String, String> header : headers.entrySet()) {
					conn.setRequestProperty(header.getKey(), header.getValue());
				}
			}
			conn.connect();
			// 遍历所有的响应头字段
			Map<String, List<String>> map = conn.getHeaderFields();
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
			String line;
			while ((line = in.readLine()) != null) {
				response.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
			}
		}
		return response.toString();
	}

	/**
	 * 发送HTTP POST请求
	 * */
	public static String doPost(String url, String content, Map<String, String> headers, String charset) {
		StringBuffer response = new StringBuffer();
		OutputStream out = null;
		BufferedReader in = null;
		try {
			// 打开和URL之间的连接
			URLConnection conn = (new URL(url)).openConnection();
			conn.setReadTimeout(READ_TIMEOUT);
			conn.setConnectTimeout(CONNECT_TIMEOUT);
			// 设置通用的请求属性
			if (headers != null) {
				for (Map.Entry<String, String> header : headers.entrySet()) {
					conn.setRequestProperty(header.getKey(), header.getValue());
				}
			}
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = conn.getOutputStream();
			if (content != null) {
				out.write(content.getBytes(charset));
			}
			out.flush();

			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
			String line;
			while ((line = in.readLine()) != null) {
				response.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException ex) {
			}
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
			}
		}
		return response.toString();
	}
}
